package elitech.vietnam.weatherfashion.tabs.settings;

import java.io.IOException;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import elitech.vietnam.weatherfashion.MainActivity;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.dialog.MyProgressDialog;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.ultilities.MD5;
import elitech.vietnam.weatherfashion.ultilities.ValueOption;
import elitech.vietnam.weatherfashion.widget.NotifyButton;

public class ChangePasswordFragment extends Fragment implements OnClickListener {

	private Button btnOk;
	// private Button btnCancel;
	private EditText edtOldPassword;
	private EditText edtNewPassword;
	private EditText edtConfirmPassword;
	private MyProgressDialog mProgressDialog;
	private TextView tvThongBao;
	private Toast toast;
	private NotifyButton button_notification;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_change_password, null);
		button_notification = (NotifyButton) view.findViewById(R.id.button_notification);
		
		((MainActivity) getActivity()).setCurrentNotifyButton(button_notification);

		MemberDTO m = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (m == null)
			button_notification.setVisibility(View.GONE);
		else 
			button_notification.setVisibility(View.VISIBLE);
		//button_notification.setOnClickListener(this);

		initView(view);
		return view;
	}

	private void initView(View view) {

		/************************************/
		Button btnBack = (Button) view.findViewById(R.id.btnBack);
		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// getFragmentManager()
				// .beginTransaction()
				// .replace(R.id.container_framelayout,
				// new SettingsFragment()).commit();
				getActivity().onBackPressed();
			}
		});
		/**************************/
		tvThongBao = (TextView) view.findViewById(R.id.tvThongBao);

		/************************/
		edtOldPassword = (EditText) view.findViewById(R.id.edtOldPassword);
		edtNewPassword = (EditText) view.findViewById(R.id.edtNewPassword);
		edtConfirmPassword = (EditText) view
				.findViewById(R.id.edtConfirmPassword);

		/************************/
		btnOk = (Button) view.findViewById(R.id.btnOk);
		btnOk.setOnClickListener(this);

		// /************************/
		// btnCancel = (Button) view.findViewById(R.id.btnCancel);
		// btnCancel.setOnClickListener(this);

		/**************************/
		mProgressDialog = new MyProgressDialog(getActivity());
		mProgressDialog.setCancelable(false);

		focusView(edtOldPassword);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnOk:
			excuteChangePassword();
			break;
		// case R.id.btnCancel:
		// getFragmentManager()
		// .beginTransaction()
		// .replace(R.id.container_framelayout, new SettingsFragment())
		// .commit();
		//
		// break;

		case R.id.button_notification:
			Log.w("Notification", "Num Count: " + WFApplication.getInstance().mListNoti.size());
			((MainActivity) getActivity()).mNotiWindow.showAsDropDown(button_notification);
			((MainActivity) getActivity()).mNotiWindow.notifyDataChanged();
			button_notification.setNumber(0);
			break;

		default:
			break;
		}
	}

	private void excuteChangePassword() {
		if (checkDataInput()) {

			MemberDTO user = GlobalValue.getInstance(getActivity())
					.readUserInfo();
			String username = user.getMemberUsername();
			String oldPass = edtOldPassword.getText().toString();
			String newPass = edtNewPassword.getText().toString();

			new ChangePasswordAsynTask().execute(username, oldPass, newPass);
		}
	}

	private boolean checkDataInput() {
		String oldPass = edtOldPassword.getText().toString();
		String newPass = edtNewPassword.getText().toString();
		String confirmPass = edtConfirmPassword.getText().toString();

		if (oldPass.equals("")) {
			focusView(edtOldPassword);
			showToast(getResources().getString(
					R.string.setting_old_password_request));
			thongBao(getResources().getString(
					R.string.setting_old_password_request));
			return false;
		}
		if (newPass.equals("")) {
			showToast(getResources().getString(
					R.string.setting_new_password_request));
			thongBao(getResources().getString(
					R.string.setting_new_password_request));

			focusView(edtNewPassword);
			return false;
		}
		if (confirmPass.equals("")) {
			showToast(getResources().getString(
					R.string.setting_confirm_password_request));
			thongBao(getResources().getString(
					R.string.setting_confirm_password_request));
			focusView(edtConfirmPassword);
			return false;
		}
		if (newPass.equals(confirmPass) == false) {
			showToast(getResources().getString(
					R.string.setting_confirm_password_false));
			thongBao(getResources().getString(
					R.string.setting_confirm_password_false));
			focusView(edtConfirmPassword);
			return false;
		}
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (MD5.md5(oldPass).equals(user.getMemberPassword()) == false) {
			focusView(edtOldPassword);
			showToast(getResources().getString(
					R.string.setting_old_password_false));
			thongBao(getResources().getString(
					R.string.setting_old_password_false));
			return false;
		}
		if (newPass.equals(oldPass)) {
			focusView(edtNewPassword);
			showToast(getResources().getString(
					R.string.setting_old_password_like_new_password));
			thongBao(getResources().getString(
					R.string.setting_old_password_like_new_password));
			return false;
		}
		return true;
	}

	private void focusView(EditText view) {
		view.selectAll();
		view.requestFocus();
	}

	private void showToast(String mess) {
		if (toast == null) {
			toast = Toast.makeText(getActivity(), mess, Toast.LENGTH_SHORT);
		} else {
			toast.setText(mess);
		}
		toast.show();
	}

	private void thongBao(String mess) {
		tvThongBao.setText(mess);
	}

	private class ChangePasswordAsynTask extends
			AsyncTask<String, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			String username = params[0];
			String oldPass = params[1];
			String newPass = params[2];

			PHPSoapServiceCaller phpService = new PHPSoapServiceCaller();
			boolean response = false;
			try {
				response = phpService
						.changePassword(username, oldPass, newPass);
			} catch (IOException e) {
				e.printStackTrace();
			}
			MemberDTO user = GlobalValue.getInstance(getActivity())
					.readUserInfo();
			if (response) {
				user.setMemberPassword(MD5.md5(newPass));
				GlobalValue.getInstance(getActivity()).writeUserInfo(user);
				
				// Save member info login
				ValueOption option = GlobalValue.getInstance(getActivity())
						.readOptionInfo();
				if (option.isAutoLogin()) {
					option.setUsername(username);
					option.setPassword(newPass);
					GlobalValue.getInstance(getActivity()).writeOptionInfo(
							option);
					// FileOption fileOption = new FileOption(getActivity());
					// fileOption.WriteOption(option);
				}
			}

			return response;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			if (result) {

				// hide keyboard
				InputMethodManager inputManager = (InputMethodManager) getActivity()
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				inputManager.hideSoftInputFromWindow(getActivity()
						.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				//

				showToast(getResources().getString(
						R.string.setting_change_password_success));

				// tvThongBao.setText(R.string.setting_change_password_success);
				getActivity().onBackPressed();

			} else {
				focusView(edtOldPassword);
				showToast(getResources().getString(
						R.string.setting_change_password_fail));
				thongBao(getResources().getString(
						R.string.setting_change_password_fail));
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
		}
	}

}
